<?php
/**
 * 角色权限判断
 */

namespace App\Http\Middleware;

use App\Models\Account\Role;
use Closure;
use Exception;

class Permission
{
    /**
     * Handle an incoming req.
     *
     * @param  \Illuminate\Http\Request  $req
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($req, Closure $next)
    {
        // TODO 线下环境建设功能免权限校验的用户, 线上留用户可以设置
        if(env('APP_ENV') != 'production' && in_array($req->uid, ['25','240'])){
            return $next($req);
        }else{
            if(in_array($req->rid, ['1','9','29'])){
                return $next($req);
            }
        }
        $roleFuns = Role::find($req->rid)->functions
        ->map(function($item){
            return $item['path'];
        })->reject(function($item){
            return empty($item);
        })->flip();
        // dd($roleFuns->has($req->path()));
        if(empty($roleFuns) || !$roleFuns->has('/'.$req->path())){
            throw new Exception("Access Forbidden", 403);
        }
        return $next($req);
    }
}
